//
//  LoginViewController.m
//  HuLaQuan
//
//  Created by hok on 1/7/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "LoginViewController.h"

//Logic Modal
#import "LoginEngine.h"
#import "PrepareAppEngine.h"

//Views
#import "YuLoginInputInfoField.h"


//Header
#import "LoginRelatedHeader.h"

//
#import "YuLoginRegisterUtilities.h"

@interface LoginViewController()

@property (nonatomic, strong) LoginEngine *loginEngine;
@property (nonatomic, strong) PrepareAppEngine *prepareAppEngine;


@property (weak, nonatomic) IBOutlet YuLoginInputInfoField *secretField;
@property (weak, nonatomic) IBOutlet YuLoginInputInfoField *nameField;

@property (weak, nonatomic) IBOutlet UIButton *forgetSecret;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@property (weak, nonatomic) IBOutlet UIButton *fastRegister;



@end
@implementation LoginViewController
- (PrepareAppEngine *)prepareAppEngine
{
    if(!_prepareAppEngine) _prepareAppEngine = [[PrepareAppEngine alloc] init];
    return _prepareAppEngine;
}
- (LoginEngine *)loginEngine
{
    if(!_loginEngine) _loginEngine = [[LoginEngine alloc] init];
    return _loginEngine;
}

-(void) viewDidLoad
{
    [super viewDidLoad];
}
#pragma mark - Init UI
- (void)setupUI
{
    // setup Tap Gesture For Resign Keyboard
    [self setupTapGesture];
    
    // setup UnderLine For Two Buttons
    [self setupButtonUnderLine];
    
    //setup Placeholder For Input Fields
    [self setupTextField];
    
    self.loginButton.enabled = NO;
    
    self.title = @"登录";
}

- (void)setupButtonUnderLine
{
    [self setupUnderLineForButton: self.forgetSecret];
    [self setupUnderLineForButton: self.fastRegister];
}
- (void)setupUnderLineForButton:(UIButton *)button;
{
    NSMutableAttributedString *str = [button.titleLabel.attributedText mutableCopy];
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [str length])];
    [button setAttributedTitle:str forState:UIControlStateNormal];
}
- (void)setupTextField
{
//    self.nameField.imageName = @"name.png";
//    self.secretField.imageName = @"password.png";
    [self.nameField setColorfulPlaceholder:kUsernameFieldPlaceholder];
    [self.secretField setColorfulPlaceholder:kPasswordFieldPlaceholder];
}


#pragma mark - Textfield delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    YuLoginInputInfoField *textF = (YuLoginInputInfoField *)textField;
    [textF setColorfulPlaceholder:@""];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.text.length == 0 ) {
        YuLoginInputInfoField *textF = (YuLoginInputInfoField *)textField;
        [textF setColorfulPlaceholder:([textField isEqual:self.nameField] ? kUsernameFieldPlaceholder : kPasswordFieldPlaceholder)];
        
    }
    if (self.nameField.text.length == 0 || self.secretField.text.length == 0) {
        self.loginButton.enabled = NO;
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (self.nameField.text.length > 0 && self.secretField.text.length > 0) {
        self.loginButton.enabled = YES;
    }
    return YES;
    
    // return [self validateNumber:string];
}

#pragma mark - Login Events
- (IBAction)tapLoginButton:(id)sender {
    
  //  [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    if([YuLoginRegisterUtilities isMobileNumber:self.nameField.text]){
        [KVNProgress showWithStatus:NETWORK_LOADING];
        
        [self.loginEngine loginWithUsername:self.nameField.text andPassword:self.secretField.text];
    }else{
        [self.view makeToast:kMobileNumberInavalid];
    }
    
    
}


- (void)loginFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"TabBar" bundle:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self presentViewController:[storyBoard instantiateViewControllerWithIdentifier:@"HomeTabBarController"] animated:NO completion:nil];
            
            
        });
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
    
}
- (void)prepareAppFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        NSLog(@"准备好啦");
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
    
}


#pragma mark - controller lifecycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
   // [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFinish:) name:@"LoginFinish" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(prepareAppFinish:) name:@"PrepareAppFinish" object:nil];
    
    [self.prepareAppEngine prepareAppLoading];
//    if ([CurrentUser sharedInstance].name) {
//        self.nameField.text = [CurrentUser sharedInstance].name;
//    }
//    
//    [MobClick beginLogPageView:@"LoginView"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"LoginFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PrepareAppFinish" object:nil];

//    [MobClick endLogPageView:@"LoginView"];
}

//alert eg
//UIAlertController *x = [UIAlertController alertWithTitle:@"版本更新" andMessage:@"有新的版本的余物宝，请下载" andBlock:^(UIAlertAction *action ) {
//    ////NSLog(@"%@",action.title);
//    if ([action.title isEqualToString:@"好的"]) {
//        [VersionUpdateEngine gotoAPPStoreUpdate:item];
//    }
//    
//} type:@"confirmAndCancel"];
/* UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"获取账户余额失败" andBlock:nil type:@"confirm"];
 [self presentViewController:x animated:YES completion:nil];*/


@end
